const app = getApp();
const API_BASE = 'http://127.0.0.1/zone';

/**
 * 网络请求方法
 * @param url {string} 请求url
 * @param data {object} 参数
 * @returns {Promise}
 */
function postJson(url, data) {
  return request(url, data, 'POST');
}

function postForm(url, data) {
  return request(url, data, 'POST', 'application/x-www-form-urlencoded');
}

function request(url, data, method, contentType) {
  return new Promise(function(resolve, reject) {
    wx.showLoading();
    wx.request({
      url: API_BASE + url,
      data: data || {},
      method: method ? method : 'GET',
      header: {
        'token': wx.getStorageSync('token'),
        'Content-Type': contentType ? contentType : 'application/json'
      },
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          if (res.data.retCode == 200) {
            resolve(res.data);
          } else {
            if (res.data.retCode == 9000) {
              wx.redirectTo({
                url: '../login/login',
              })
            } else {
              wx.showToast({
                title: res.data.retMsg,
                duration: 3000
              });
              reject();
            }
          }
        } else {
          wx.showToast({
            title: `请求错误 ${res.statusCode}`,
            duration: 3000
          });
          reject();
        }
      },
      fail: function() {
        wx.hideLoading();
        wx.showToast({
          title: '请求失败',
          duration: 3000
        });
        reject();
      }
    });
  });
}

function uploadFile(url, filePath, name, cb) {
  wx.showLoading();
  wx.uploadFile({
    url: API_BASE + url,
    filePath: filePath,
    name: name,
    header: {
      'token': wx.getStorageSync('token'),
      'content-type': 'multipart/form-data'
    },
    success: function(res) {
      wx.hideLoading();
      if (res.statusCode == 200) {
        var data = JSON.parse(res.data);
        if (data.retCode == 200) {
          return typeof cb == "function" && cb(data)
        } else {
          wx.showToast({
            title: data.retMsg,
            duration: 3000
          });
          return typeof cb == "function" && cb(false)
        }

      } else {
        wx.showToast({
          title: `请求错误 ${res.statusCode}`,
          duration: 3000
        });
        return typeof cb == "function" && cb(false)
      }
    },
    fail: function() {
      wx.hideLoading();
      wx.showToast({
        title: '请求失败',
        duration: 3000
      });
      return typeof cb == "function" && cb(false)
    }
  })
}

module.exports = {
  getData: url => {
    return request(url)
  },
  postJson: postJson,
  postForm: postForm,
  uploadFile: uploadFile,
  login: data => {
    postForm('/app/login.json', data).then(res => {
      wx.setStorageSync('token', res.token)
      wx.reLaunch({
        url: '../user/user',
      })
    }).catch(() => {});
  },
  logout: () => {
    request('/app/logout.json').then(res => {}).catch(() => {});
    wx.removeStorageSync('token');
    wx.redirectTo({
      url: '../login/login',
    })
  }
};